package health.carousel.parsers;

import health.carousel.data.PositionDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;
import java.io.IOException;

public class ParallonPositionDetailsParser extends PositionDetailsParser {
    private static final Logger log = LoggerFactory.getLogger(ParallonPositionDetailsParser.class);


    public PositionDetails parsePositionDetails(String line, String seeking) throws MessagingException,
            IOException {

        String dotsDelimiter = "\\.\\.\\.";
        if (!line.contains("...")) {
            dotsDelimiter = "…";
        }
        String toStartDelimiter = " to start ";
        String spaceDelimiter = " ";

        //get additional details
        String lineToSplit = line.replace((char) 160, ' ').replaceAll("\\s+", " ").trim();
        String[] splittedParts = lineToSplit.split(dotsDelimiter, 2);
        String additionalDetailsPart = splittedParts.length > 1
                ? splittedParts[1].replaceAll("\\.", "").replaceAll("…", "").trim()
                : "";

        //get start date
        lineToSplit = splittedParts[0];
        splittedParts = lineToSplit.split(toStartDelimiter, 2);
        String startDate = splittedParts[1];

        //get quantity
        lineToSplit = splittedParts[0];
        splittedParts = lineToSplit.split(spaceDelimiter);
        Integer quantity = Integer.parseInt(splittedParts[0]);

        //get shift time
        String shiftTime = splittedParts[1];

        String facility = "";
        String classification = "";

        for (int partIndex = 2; partIndex < splittedParts.length; partIndex++) {
            String value = splittedParts[partIndex];
            if (partIndex < splittedParts.length - 1) {
                //get facility
                facility += value + " ";
            } else {
                //get classification
                classification = value;
            }
        }

        //get requestor
        String requestor = seeking
                .replaceAll(", is seeking:", "")
                .replaceAll(", is seeking", "")
                .replaceAll(" is seeking", "")
                .replaceAll(", is.*?seeking:", "")
                .replaceAll(",is.*?seeking", "")
                .replaceAll("is.*?seeking:", "")
                .replaceAll("is.*?seeking", "");

        return new PositionDetails(
                quantity,
                shiftTime,
                null,
                null,
                facility.trim(),
                classification,
                startDate,
                requestor,
                additionalDetailsPart,
                line);
    }

}
